
package com.mego.zbss.activity_fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mego.zbss.R;
import com.mego.zbss.util.Constant;
import com.mego.zbss.view.BaseViewHolder;
import com.mego.zbss.view.slideLayoutRelative;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnBottomDragListener;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.ui.TopMenuWindow;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.StringUtil;

/**
 * 通用网页Activity
 *
 * @author Lemon
 * @use toActivity(WebViewActivity.createIntent(...));
 */
public class SWebViewActivity2 extends BaseActivity implements OnBottomDragListener, OnClickListener,
        AlertDialog.OnDialogButtonClickListener, View.OnTouchListener {
    public static final String TAG = "SWebViewActivity2";

    public static final String INTENT_RETURN = "INTENT_RETURN";
    public static final String INTENT_URL = "INTENT_URL";

    /**
     * 获取启动这个Activity的Intent
     *
     * @param title
     * @param url
     */
    public static Intent createIntent(Context context, String title, String url) {
        return new Intent(context, SWebViewActivity2.class).
                putExtra(SWebViewActivity2.INTENT_TITLE, title).
                putExtra(SWebViewActivity2.INTENT_URL, url);
    }


    @Override
    public Activity getActivity() {
        return this;
    }

    private String mUrl;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sweb2_view_activity, this);//传this是为了全局滑动返回

        mUrl = StringUtil.getCorrectUrl(getIntent().getStringExtra(INTENT_URL));
        if (StringUtil.isNotEmpty(mUrl, true) == false) {
            Log.e(TAG, "initData  StringUtil.isNotEmpty(url, true) == false >> finish(); return;");
            enterAnim = exitAnim = R.anim.null_anim;
            finish();
            return;
        }

        tvBaseTitle.setText("钻豹视商-大陆");
        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private ProgressBar pbWebView;
    private WebView wvWebView;

    static final int SLIDE_SPEED = 30;
    static final int MSG_INIT_DEV = 200001;

    boolean bIsScrolling = false;
    int iLimited = 0, mScroll = 0;

    GestureDetector mGestureDetector = null;

    LinearLayout mainLayout = null;
    LinearLayout leftLayout = null;
    slideLayoutRelative layoutSlideMenu = null;
    ListView mListSettings = null;
    TextView change_name;
    MyAdapter mMyAdapter;

    @Override
    public void initView() {
        autoSetTitle();

        pbWebView = (ProgressBar) findViewById(R.id.pbWebView);
        wvWebView = (WebView) findViewById(R.id.wvWebView);

        mainLayout = (LinearLayout) findViewById(R.id.llWebView);
        mainLayout.setOnTouchListener(this);
        leftLayout = (LinearLayout) findViewById(R.id.leftLayoutData);
        leftLayout.setOnTouchListener(this);

        ImageView change_icon = (ImageView) findViewById(R.id.change_icon);
        change_name = (TextView) findViewById(R.id.change_name);
        change_icon.setImageResource(settings_icons[7]);
        change_name.setText(TOP_MENUS[7]);

        layoutSlideMenu = (slideLayoutRelative) findViewById(R.id.layoutSlideMenuData);
        layoutSlideMenu.setOnScrollListener(new slideLayoutRelative.OnScrollListener() {
            @Override
            public void doOnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                onSlideScroll(distanceX);
            }

            @Override
            public void doOnRelease() {
                onRelease();
            }
        });
        mListSettings = (ListView) findViewById(R.id.settings_list);
        mMyAdapter = new MyAdapter(this);
        mListSettings.setAdapter(mMyAdapter);
        mListSettings.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                onSettingItem(position);
            }
        });
        mGestureDetector = new GestureDetector(new GestureDetector.OnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                bIsScrolling = false;
                mScroll = 0;
                iLimited = 0;
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
                if (lp.leftMargin > 0) {
                    iLimited = 1;
                } else if (lp.leftMargin < 0) {
                    iLimited = -1;
                }
                return true;
            }

            @Override
            public void onShowPress(MotionEvent e) {
            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                onSlideScroll(distanceX);
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {
            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                return false;
            }
        });

        mGestureDetector.setIsLongpressEnabled(false);
        DisplayMetrics dm = getResources().getDisplayMetrics();

        RelativeLayout.LayoutParams lp1 = (RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
        RelativeLayout.LayoutParams lp2 = (RelativeLayout.LayoutParams) leftLayout.getLayoutParams();
        lp1.width = dm.widthPixels;
        mainLayout.setLayoutParams(lp1);

        lp2.leftMargin = -lp2.width;
        leftLayout.setLayoutParams(lp2);
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    @SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
    @Override
    public void initData() {

        WebSettings webSettings = wvWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        wvWebView.requestFocus();

        // 设置setWebChromeClient对象
        wvWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
//                tvBaseTitle.setText(StringUtil.getTrimedString(title));
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                pbWebView.setProgress(newProgress);
            }
        });

        wvWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                wvWebView.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
//                tvBaseTitle.setText(StringUtil.getTrimedString(wvWebView.getUrl()));
                pbWebView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                tvBaseTitle.setText(StringUtil.getTrimedString(wvWebView.getTitle()));
                pbWebView.setVisibility(View.GONE);
            }
        });

        wvWebView.loadUrl(mUrl);
    }


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initEvent() {

//        tvBaseTitle.setOnClickListener(this);
    }

    private static final String[] TOP_MENUS = {
            "商城入口", "入驻商户", "钻石商城", "团购", "优惠卷中心",
            "我的收藏", "申请入驻全返利商城", "切换至钻豹台湾商城"};

    private static final String[] TOP_MENUS_TW = {
            "商城入口", "入駐商戶", "鉆石商城", "團購", "優惠卷中心",
            "我的收藏", "申請入駐全返利商城", "切換至鉆豹大陸商城"};

    boolean _isTW = false;

    @Override
    public void onDragBottom(boolean rightToLeft) {
        if (rightToLeft) {
            if (wvWebView.canGoForward()) {
                wvWebView.goForward();
            }
            return;
        }
//		onBackPressed();
    }

    private void doChange(boolean isTW) {
        _isTW = isTW;
        mUrl = getWebByIndex(0);
        wvWebView.loadUrl(mUrl);
        if (isTW) {
            change_name.setText(TOP_MENUS_TW[7]);
        } else {
            change_name.setText(TOP_MENUS[7]);
        }
    }

    public void onChangeTW(View v) {
        doChange(!_isTW);
        mMyAdapter.notifyDataSetChanged();
        onMenu(null);
    }

    boolean flag_clicked = false;
    Timer click_timer = null;
    TimerTask click_timer_task = null;

    public void onMenu(View view) {
        if (flag_clicked == true) {
            return;
        }
        flag_clicked = true;

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
        if (lp.leftMargin == 0) {
            new SlideMenu().execute(leftLayout.getLayoutParams().width, SLIDE_SPEED);
        } else {
            new SlideMenu().execute(leftLayout.getLayoutParams().width, -SLIDE_SPEED);
        }

        click_timer = new Timer();
        click_timer_task = new TimerTask() {
            public void run() {
                flag_clicked = false;
                click_timer_task.cancel();
                click_timer.cancel();
            }
        };
        if ((click_timer == null) || (click_timer_task == null)) {
            SystemClock.sleep(1000);
            flag_clicked = false;
        } else {
            click_timer.schedule(click_timer_task, 1000);
        }
    }

    private String getWebByIndex(int index) {
        tvBaseTitle.setText("钻豹视商-大陆");
        String url = Constant.ZBSS_WEBSITE_0;
        switch (index) {
            default:
            case 0:
                break;
            case 1:
                url = Constant.ZBSS_WEBSITE_1;
                break;
            case 2:
                url = Constant.ZBSS_WEBSITE_2;
                break;
            case 3:
                url = Constant.ZBSS_WEBSITE_3;
                break;
            case 4:
                url = Constant.ZBSS_WEBSITE_4;
                break;
            case 5:
                url = Constant.ZBSS_WEBSITE_5;
                break;
            case 6:
                url = Constant.ZBSS_WEBSITE_6;
                break;
        }

        if (_isTW) {
            url = url.replace("mego_shopv2", "mego_shopv2_tw");
            url = url.replace("?i=12&", "?i=3&");
            tvBaseTitle.setText("鉆豹視商-臺灣");
        }

        return url;
    }

    @Override
    public void onReturnClick(View v) {
        finish();
    }

    @Override
    public void onForwardClick(View v) {
        if (_isTW) {
            toActivity(TopMenuWindow.createIntent(context, TOP_MENUS_TW), REQUEST_TO_TOP_MENU, false);
        } else {
            toActivity(TopMenuWindow.createIntent(context, TOP_MENUS), REQUEST_TO_TOP_MENU, false);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tvBaseTitle) {
            toActivity(EditTextInfoWindow.createIntent(context
                    , EditTextInfoWindow.TYPE_WEBSITE
                    , StringUtil.getTrimedString(tvBaseTitle)
                    , wvWebView.getUrl()),
                    REQUEST_TO_EDIT_TEXT_WINDOW, false);
        }
    }

    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void onBackPressed() {
        if (wvWebView.canGoBack()) {
            wvWebView.goBack();
            return;
        }

        super.onBackPressed();
    }

    //类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    protected void onPause() {
        super.onPause();
        wvWebView.onPause();
    }

    @Override
    protected void onResume() {
        wvWebView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (wvWebView != null) {
            wvWebView.destroy();
            wvWebView = null;
        }
        wvWebView = null;
    }

    private long firstTime = 0;//第一次返回按钮计时

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK: {
                if (wvWebView.canGoBack()) {
                    wvWebView.goBack();
                    firstTime = 0;
                } else {
                    long secondTime = System.currentTimeMillis();
                    if (secondTime - firstTime > 2000) {
                        showShortToast("再按一次退出");
                        firstTime = secondTime;
                    } else {//完全退出
                        moveTaskToBack(false);//应用退到后台
                        System.exit(0);
                    }
                }
            }
            break;
        }
        return super.onKeyUp(keyCode, event);
    }

    protected static final int REQUEST_TO_EDIT_TEXT_WINDOW = 1;
    private static final int REQUEST_TO_TOP_MENU = 30;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            default:
            case REQUEST_TO_EDIT_TEXT_WINDOW:
                if (data != null) {
                    wvWebView.loadUrl(StringUtil.getCorrectUrl(data.getStringExtra(EditTextInfoWindow.RESULT_VALUE)));
                }
                break;
            case REQUEST_TO_TOP_MENU:
                if (data != null) {
                    int index = data.getIntExtra(TopMenuWindow.RESULT_POSITION, -1);
                    if (index == 7) {
                        doChange(!_isTW);
                    } else if (index >= 0 && index < 7) {
                        mUrl = getWebByIndex(index);
                        wvWebView.loadUrl(mUrl);
                    }
                }
                break;
        }
    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        switch (requestCode) {
            default:
            case 0:
//				if (data != null) {
//					wvWebView.loadUrl(StringUtil.getCorrectUrl(data.getStringExtra(EditTextInfoWindow.RESULT_VALUE)));
//				}
                break;
        }
    }

    private void onSettingItem(int position) {
        if (position == 7) {
            doChange(!_isTW);
        } else if (position >= 0 && position < 7) {
            mUrl = getWebByIndex(position);
            wvWebView.loadUrl(mUrl);
        }
        onMenu(null);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if ((MotionEvent.ACTION_UP == event.getAction()) && bIsScrolling) {
            onRelease();
        }
        return mGestureDetector.onTouchEvent(event);
    }

    void rollLayout(int margin) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
        lp.leftMargin += margin;
        lp.rightMargin -= margin;
        mainLayout.setLayoutParams(lp);
        lp = (RelativeLayout.LayoutParams) leftLayout.getLayoutParams();
        lp.leftMargin += margin;
        leftLayout.setLayoutParams(lp);
    }

    void onSlideScroll(float distanceX) {
        bIsScrolling = true;
        mScroll += distanceX;

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
        RelativeLayout.LayoutParams lpLeft = (RelativeLayout.LayoutParams) leftLayout.getLayoutParams();

        int distance = 0;
        if (mScroll > 0) { // move leftward
            if (lp.leftMargin > 0) { // close slide menu
                distance = lp.leftMargin;
            }
            if (mScroll >= distance) {
                mScroll = distance;
            }
        } else if (mScroll < 0) { // move rightward
            if (lp.leftMargin >= 0) { // open slide menu
                if (iLimited < 0) {
                    return;
                }
                distance = lpLeft.width - Math.abs(lp.leftMargin);
            }
            if (mScroll <= -distance) {
                mScroll = -distance;
            }
        }
        if (mScroll != 0) {
            rollLayout(-mScroll);
        }
    }

    void onRelease() {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
        if (lp.leftMargin < 0) {
            new SlideMenu().execute(Math.abs(lp.leftMargin), SLIDE_SPEED);
        } else if (lp.leftMargin > 0) {
            if (Math.abs(lp.leftMargin) > leftLayout.getLayoutParams().width / 2) {
                new SlideMenu().execute(leftLayout.getLayoutParams().width - Math.abs(lp.leftMargin), SLIDE_SPEED);
            } else {
                new SlideMenu().execute(Math.abs(lp.leftMargin), -SLIDE_SPEED);
            }
        }
    }

    public class SlideMenu extends AsyncTask<Integer, Integer, Void> {
        @Override
        protected Void doInBackground(Integer... params) {
            if (params.length == 2) {
                int times = params[0] / Math.abs(params[1]);
                if (params[0] % Math.abs(params[1]) != 0) {
                    times++;
                }
                for (int i = 0; i < times; i++) {
                    publishProgress(params[0], params[1], i + 1);
                    SystemClock.sleep(10);
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            if (values.length == 3) {
                int distance = Math.abs(values[1]) * values[2];
                int delta = values[0] - distance;
                int leftMargin = 0;
                if (values[1] < 0) {
                    leftMargin = (delta > 0 ? values[1] : -(Math.abs(values[1]) - Math.abs(delta)));
                } else {
                    leftMargin = (delta > 0 ? values[1] : (Math.abs(values[1]) - Math.abs(delta)));
                }
                rollLayout(leftMargin);
            }
        }
    }
    //类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    final static public int[] settings_icons = new int[]{R.mipmap.icon08, R.mipmap.icon01, R.mipmap.icon02, R.mipmap.icon03,
            R.mipmap.icon04, R.mipmap.icon05, R.mipmap.icon06, R.mipmap.icon07};


    public class MyAdapter extends BaseAdapter {

        private Context context;
        private List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

        public MyAdapter(Context context) {
            this.context = context;
            data.clear();
            for (int i = 0; i < TOP_MENUS.length - 1 && i < settings_icons.length - 1; i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("title", TOP_MENUS[i]);
                data.add(map);
            }
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.tableitem_setting, parent, false);
            }

            ImageView settingIcon = BaseViewHolder.get(convertView, R.id.id_settingicon);
            TextView settingName = BaseViewHolder.get(convertView, R.id.id_settingname);

            if (position < settings_icons.length) {
                settingIcon.setImageResource(settings_icons[position]);
                if (_isTW) {
                    settingName.setText(TOP_MENUS_TW[position]);
                } else {
                    settingName.setText(TOP_MENUS[position]);
                }

            }
            return convertView;
        }
    }
}